package com.ruoyi.activiti.service.impl;

import com.github.pagehelper.Page;
import com.ruoyi.activiti.domain.StandingBookVo;
import com.ruoyi.activiti.mapper.StandingBookMapper;
import com.ruoyi.activiti.service.IProcessService;
import com.ruoyi.activiti.service.StandingBookService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author zeo
 * @explain 台账业务Service业务层处理
 * @date 2020/10/14 14:40
 */
@Service
@Transactional
public class StandingBookServiceImpl implements StandingBookService {

    @Autowired
    StandingBookMapper standingBookMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private IProcessService processService;

    @Override
    public List<StandingBookVo> selectStandingBookList(StandingBookVo standingBookVo) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        Page<StandingBookVo> list = (Page<StandingBookVo>) standingBookMapper.selectStandingBookList(standingBookVo);
        Page<StandingBookVo> returnList = new Page<>();
        for (StandingBookVo standingBook : list) {
            //根据创建者用户名，获取到用户信息
            SysUser sysUser = userMapper.selectUserByLoginName(standingBook.getCreateBy());
            if (sysUser != null) {
                //从用户信息中拿到用户姓名存在CreateUserName(创建人姓名)中
                standingBook.setCreateUserName(sysUser.getUserName());
            }
            //根据申请人用户名，获取到用户信息
            SysUser sysUser2 = userMapper.selectUserByLoginName(standingBook.getApplyUser());
            if (sysUser2 != null) {
                //从用户信息中拿到用户姓名存在ApplyUserName(申请人姓名)中
                standingBook.setApplyUserName(sysUser2.getUserName());
            }
            //如果流程未提交，则业务表中没有InstanceId字段，代表没有启动流程
            if (StringUtils.isNotBlank(standingBook.getInstanceId())) {
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(standingBook.getInstanceId())
                        .list();
                //如果启动的流程，在工作流表中又没找到此工作流，代表已经结束或者撤销了
                if (!CollectionUtils.isEmpty(taskList)) {
                    TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
                    standingBook.setTaskId(task.getId());
                    //取工作流表中的状态(1.正常 2.挂起) 正常就取任务名称
                    if (task.getSuspensionState() == 2) {
                        //赋值给业务类中自定义的标量
                        standingBook.setTaskName("已挂起");
                        standingBook.setSuspendState("2");
                    } else {
                        standingBook.setTaskName(task.getName());
                        standingBook.setSuspendState("1");
                    }
                } else {
                    // 已办结或者已撤销
                    standingBook.setTaskName("已结束");
                }
            } else {
                standingBook.setTaskName("未启动");
            }
            returnList.add(standingBook);
        }
        returnList.setTotal(CollectionUtils.isEmpty(list) ? 0 : list.getTotal());
        returnList.setPageNum(pageNum);
        returnList.setPageSize(pageSize);
        return returnList;
    }

    @Override
    public int insertStandingBook(StandingBookVo standingBookVo) {
        standingBookVo.setCreateBy(ShiroUtils.getLoginName());
        standingBookVo.setCreateTime(DateUtils.getNowDate());
        return standingBookMapper.insertStandingBook(standingBookVo);
    }

    @Override
    public int remove(String ids) {
        String[] idSplit = ids.split(",");
        int num = 0;
        for (String id : idSplit) {
            num += standingBookMapper.remove(id);
        }
        return num;
    }

    @Override
    public StandingBookVo selectStandingBookById(String id) {
        return standingBookMapper.selectStandingBookById(id);
    }

    @Override
    public int updateStandingBook(StandingBookVo standingBookVo) {
        standingBookVo.setUpdateTime(DateUtils.getNowDate());
        return standingBookMapper.updateStandingBook(standingBookVo);
    }

    @Override
    public String maxNumber(StandingBookVo standingBookVo) {
        return standingBookMapper.maxNumber(standingBookVo);
    }

    /**
     * 启动流程
     *
     * @param entity
     * @param applyUserId
     * @return
     */
    @Override
    public ProcessInstance submitApply(StandingBookVo entity, String applyUserId, String key, Map<String, Object> variables) {
        entity.setApplyUser(applyUserId);
        entity.setApplyTime(DateUtils.getDateStr());
        entity.setUpdateBy(applyUserId);
        standingBookMapper.updateStandingBook(entity);
        // 实体类 ID，作为流程的业务 key
        String businessKey = entity.getId().toString();
        ProcessInstance processInstance = processService.submitApply(applyUserId, businessKey, entity.getProName(), entity.getAuditContent(), key, variables);
        String processInstanceId = processInstance.getId();
        // 建立双向关系
        entity.setInstanceId(processInstanceId);
        standingBookMapper.updateStandingBook(entity);
        return processInstance;
    }
}
